/**
 * 新闻公告模块Store
 * 负责管理新闻公告相关的UI状态
 */
const dayjs = require('dayjs');
const { observable, action } = require('mobx-miniprogram');

// 新闻公告模块Store
export const newsStore = observable({
  // 新闻公告列表数据
  newsList: [],
  
  // 当前选中的新闻公告
  currentNews: null,
  
  // 新闻公告分类
  categories: [],
  
  // 过滤条件
  filter: {
    category: '',
    isTop: false,
    searchKey: '',
    sortBy: 'createTime',
    sortOrder: 'desc',
    dateRange: null
  },
  
  // 最近查看的新闻
  recentViewed: [],
  
  // 重要通知
  importantNotices: [],
  
  // 统计数据
  statistics: {
    total: 0,
    byCategory: {},
    recentAdded: 0,
    topCount: 0,
    unreadCount: 0
  },
  
  // 页面加载状态
  loading: false,
  
  // 阅读状态记录
  readStatus: {},
  
  // 计算属性：筛选后的新闻公告列表
  get filteredNews() {
    if (!this.newsList.length) return [];
    
    let filtered = [...this.newsList];
    
    // 根据分类筛选
    if (this.filter.category) {
      filtered = filtered.filter(n => n.category === this.filter.category);
    }
    
    // 根据置顶状态筛选
    if (this.filter.isTop) {
      filtered = filtered.filter(n => n.isTop);
    }
    
    // 根据关键词搜索
    if (this.filter.searchKey) {
      const key = this.filter.searchKey.toLowerCase();
      filtered = filtered.filter(n => 
        n.title.toLowerCase().includes(key) || 
        n.content.toLowerCase().includes(key) ||
        (n.author && n.author.toLowerCase().includes(key))
      );
    }
    
    // 根据日期范围筛选
    if (this.filter.dateRange && this.filter.dateRange.start && this.filter.dateRange.end) {
      const startDate = dayjs(this.filter.dateRange.start).startOf('day');
      const endDate = dayjs(this.filter.dateRange.end).endOf('day');
      
      filtered = filtered.filter(n => {
        const createTime = dayjs(n.createTime);
        return createTime.isAfter(startDate) || createTime.isSame(startDate) && 
               (createTime.isBefore(endDate) || createTime.isSame(endDate));
      });
    }
    
    // 排序
    filtered.sort((a, b) => {
      // 首先按置顶状态排序
      if (a.isTop && !b.isTop) return -1;
      if (!a.isTop && b.isTop) return 1;
      
      const field = this.filter.sortBy;
      const order = this.filter.sortOrder === 'asc' ? 1 : -1;
      
      if (field === 'createTime' || field === 'updateTime') {
        const dateA = dayjs(a[field]);
        const dateB = dayjs(b[field]);
        return dateA.isAfter(dateB) ? order : -order;
      } else if (field === 'viewCount') {
        return a[field] > b[field] ? order : -order;
      }
      
      return a[field] > b[field] ? order : -order;
    });
    
    return filtered;
  },
  
  // 计算属性：未读新闻列表
  get unreadNews() {
    return this.newsList.filter(n => !this.readStatus[n._id]);
  },
  
  // 计算属性：根据分类分组的新闻公告
  get newsByCategory() {
    const result = {};
    
    this.categories.forEach(category => {
      result[category.id] = this.newsList.filter(n => n.category === category.id);
    });
    
    return result;
  },
  
  // Action: 设置新闻公告列表
  setNewsList: action(function(news) {
    this.newsList = news;
    this.updateStatistics();
    this.updateImportantNotices();
  }),
  
  // Action: 设置分类
  setCategories: action(function(categories) {
    this.categories = categories;
  }),
  
  // Action: 更新统计数据
  updateStatistics: action(function() {
    const now = dayjs();
    const oneWeekAgo = now.subtract(7, 'day');
    
    // 按分类统计
    const byCategory = {};
    this.categories.forEach(category => {
      byCategory[category.id] = this.newsList.filter(n => n.category === category.id).length;
    });
    
    // 统计最近一周新增的新闻
    const recentAdded = this.newsList.filter(n => {
      const createTime = dayjs(n.createTime);
      return createTime.isAfter(oneWeekAgo) || createTime.isSame(oneWeekAgo);
    }).length;
    
    // 统计置顶新闻数量
    const topCount = this.newsList.filter(n => n.isTop).length;
    
    // 统计未读新闻数量
    const unreadCount = this.newsList.filter(n => !this.readStatus[n._id]).length;
    
    this.statistics = {
      total: this.newsList.length,
      byCategory,
      recentAdded,
      topCount,
      unreadCount
    };
  }),
  
  // Action: 更新重要通知
  updateImportantNotices: action(function() {
    // 获取置顶且最近发布的5条通知
    this.importantNotices = [...this.newsList]
      .filter(n => n.isImportant || n.isTop)
      .sort((a, b) => dayjs(b.createTime).valueOf() - dayjs(a.createTime).valueOf())
      .slice(0, 5);
  }),
  
  // Action: 设置当前新闻
  setCurrentNews: action(function(newsId) {
    const news = this.newsList.find(n => n._id === newsId);
    this.currentNews = news || null;
    
    // 如果找到了新闻，则添加到最近查看并标记为已读
    if (news) {
      this.addToRecentViewed(news);
      this.markAsRead(newsId);
    }
  }),
  
  // Action: 添加到最近查看
  addToRecentViewed: action(function(news) {
    // 检查是否已存在
    const existingIndex = this.recentViewed.findIndex(n => n._id === news._id);
    if (existingIndex >= 0) {
      // 已存在，则删除原有的
      this.recentViewed.splice(existingIndex, 1);
    }
    
    // 添加到最前面
    this.recentViewed.unshift({
      _id: news._id,
      title: news.title,
      category: news.category,
      viewTime: dayjs()
    });
    
    // 最多保留10条
    if (this.recentViewed.length > 10) {
      this.recentViewed.pop();
    }
  }),
  
  // Action: 标记为已读
  markAsRead: action(function(newsId) {
    this.readStatus[newsId] = true;
    this.updateStatistics();
  }),
  
  // Action: 批量标记为已读
  markAllAsRead: action(function() {
    this.newsList.forEach(news => {
      this.readStatus[news._id] = true;
    });
    this.updateStatistics();
  }),
  
  // Action: 添加新闻
  addNews: action(function(news) {
    this.newsList.push(news);
    this.updateStatistics();
    this.updateImportantNotices();
  }),
  
  // Action: 更新新闻
  updateNews: action(function(newsId, data) {
    const index = this.newsList.findIndex(n => n._id === newsId);
    if (index >= 0) {
      this.newsList[index] = {...this.newsList[index], ...data};
      
      // 如果当前选中的是这个新闻，也更新currentNews
      if (this.currentNews && this.currentNews._id === newsId) {
        this.currentNews = {...this.currentNews, ...data};
      }
      
      this.updateStatistics();
      this.updateImportantNotices();
    }
  }),
  
  // Action: 删除新闻
  deleteNews: action(function(newsId) {
    const index = this.newsList.findIndex(n => n._id === newsId);
    if (index >= 0) {
      this.newsList.splice(index, 1);
      
      // 如果当前选中的是这个新闻，清空currentNews
      if (this.currentNews && this.currentNews._id === newsId) {
        this.currentNews = null;
      }
      
      // 从最近查看中删除
      const recentIndex = this.recentViewed.findIndex(n => n._id === newsId);
      if (recentIndex >= 0) {
        this.recentViewed.splice(recentIndex, 1);
      }
      
      // 删除阅读状态
      delete this.readStatus[newsId];
      
      this.updateStatistics();
      this.updateImportantNotices();
    }
  }),
  
  // Action: 增加新闻浏览量
  increaseViewCount: action(function(newsId) {
    const index = this.newsList.findIndex(n => n._id === newsId);
    if (index >= 0) {
      this.newsList[index].viewCount = (this.newsList[index].viewCount || 0) + 1;
      
      // 如果当前选中的是这个新闻，也更新currentNews
      if (this.currentNews && this.currentNews._id === newsId) {
        this.currentNews.viewCount = (this.currentNews.viewCount || 0) + 1;
      }
    }
  }),
  
  // Action: 设置过滤条件
  setFilter: action(function(filter) {
    this.filter = {...this.filter, ...filter};
  }),
  
  // Action: 清空过滤条件
  clearFilter: action(function() {
    this.filter = {
      category: '',
      isTop: false,
      searchKey: '',
      sortBy: 'createTime',
      sortOrder: 'desc',
      dateRange: null
    };
  }),
  
  // Action: 设置加载状态
  setLoading: action(function(loading) {
    this.loading = loading;
  })
}); 